package juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * A 打印5次，B打印10次，并且还来轮
 * lock 精确唤醒线程
 */
class ShareResourece{
    private int number = 1;//A:1 B:2
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();

    public void print(){
        lock.lock();
        // 1 判断
        while(number != 1){
            try {
                c1.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 2 干活
        for (int i=1;i<=5;i++){
            System.out.println(Thread.currentThread().getName()+"--"+i);
        }
        // 3 通知
        number = 2;
        c2.signal();
        lock.unlock();
    }

    public void print10(){
        lock.lock();
        // 1 判断
        while(number != 2){
            try {
                c2.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 2 干活
        for (int i=1;i<=10;i++){
            System.out.println(Thread.currentThread().getName()+"--"+i);
        }
        // 3 通知
        number = 1;
        c1.signal();
        lock.unlock();
    }
}
public class MoreThread {
    public static void main(String[] args) {
        ShareResourece s = new ShareResourece();
        new Thread(()->{
            for (int i = 0; i < 2; i++) {
                s.print();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 2; i++) {
                s.print10();
            }
        },"B").start();
    }

}
